package com.gitee.chili.leisure.core;

import com.gitee.chili.leisure.exception.NettyHandlerObtainException;
import com.gitee.chili.leisure.exception.NettyHandlerRegistryException;
import com.gitee.chili.leisure.model.MessageCmdEnum;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 消息工厂
 *
 * @author week solider
 * @since 2020.08.28
 */
@Slf4j
public final class MessageHandlerFactory {

    /**
     * 消息处理器缓存
     */
    private final static Map<MessageCmdEnum.Command, MessageHandler> handlers = new ConcurrentHashMap<>(128);


    private MessageHandlerFactory() {
    }

    /**
     * 注册处理器, 实际上的 netty message 处理
     *
     * @param cmd     消息命令
     * @param handler 处理器
     */
    public static void register(MessageCmdEnum.Command cmd, MessageHandler handler) {
        try {
            handlers.put(cmd, handler);
        } catch (Exception e) {
            log.error("注册处理器: [ {} ] 失败, 命令: [ {} ]:", handler.getClass(), cmd, new NettyHandlerRegistryException(e));
        }
    }

    /**
     * 获取消息处理器
     *
     * @param cmd 消息命令
     * @return netty message handler
     */
    public static MessageHandler obtain(MessageCmdEnum.Command cmd) {

        try {
            return handlers.get(cmd);
        } catch (Exception e) {
            log.error("获取消息处理器异常 命令: [ {} ]:", cmd, new NettyHandlerObtainException(e));
        }
        return null;
    }

}
